package com.lzl.common;

import com.lzl.common.http.SimpleRequest;
import com.lzl.common.http.SimpleResponse;
import com.lzl.common.utils.SnowFlake;
import lombok.Data;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Data
public class GateWayPo {

    private Long id;

    private String appId;

    private String status;

    private long datetime;

    private SimpleRequest request;

    private SimpleResponse response;

    final public ReentrantLock lock = new ReentrantLock();
    final public Condition condition = lock.newCondition();

    public GateWayPo(SimpleRequest request) {
        this.id = SnowFlake.nextId();
        this.status = "0";
        this.request = request;
    }

    public GateWayPo() {}

    /**
     * 信号传递，等待完毕
     * @param timeout
     * @return
     * @throws InterruptedException
     */
    public boolean await(long timeout) throws InterruptedException{
        lock.lock();
        try {
            if (timeout <= 0) {
                condition.await();
                return true;
            } else {
                return condition.await(timeout, TimeUnit.SECONDS);
            }
        }  finally{
            lock.unlock();
        }
    }

    /**
     * 信号传递，完毕
     */
    public void doneSignal(){
        lock.lock(); //无竞争锁,信号传递用
        condition.signal(); //信号传递用
        lock.unlock(); //无竞争锁,信号传递用
    }
}
